package lengthOfLongestSubstring;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author hht
 * @ClassName Solution
 * @Description https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * @Date 2019/12/20 8:56
 * @VERSION 1.0
 */
public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;

    }
    public static int lengthOfLongestSubstring2(String s) {
        LinkedBlockingQueue<Character> queue = new LinkedBlockingQueue();
        int maxLength = 0;
        for(int i=0;i<s.length();i++){
            char cur = s.charAt(i);
            if(queue.contains(cur)){
                if(queue.size()>maxLength)
                    maxLength = queue.size();
                while (queue.poll()!=cur);
            }
            queue.add(cur);
        }
        int size = queue.size();
        return maxLength>=size?maxLength:size;
    }
    public static int lengthOfLongestSubstring1(String s) {
        HashSet charSet = new HashSet();
        int maxLength = 0;
        int begin = 0;
        for(int i=0;i<s.length();i++){
            char cur = s.charAt(i);
            if(charSet.contains(cur)){
                if(charSet.size()>maxLength)
                    maxLength = charSet.size();
                charSet = new HashSet();
                i = begin;
                begin ++;
            }else{
                charSet.add(cur);
            }
        }
        return maxLength>=charSet.size()?maxLength:charSet.size();
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("pwwkew"));
    }

}
